{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c4083ad6-d064-4db7-b4fc-33424563e836",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['OMP_NUM_THREADS'] = '1'\n",
    "import argparse\n",
    "import torch\n",
    "from env import create_train_env\n",
    "from model import ActorCritic\n",
    "from optimizer import GlobalAdam\n",
    "from process import local_train, local_test\n",
    "import torch.multiprocessing as _mp\n",
    "import shutil"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "eb881c4d-71a6-4c24-b4c5-c8b28f1fc986",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_args():\n",
    "    parser = argparse.ArgumentParser()\n",
    "    parser.add_argument(\"--world\", type=int, default=1)\n",
    "    parser.add_argument(\"--stage\", type=int, default=1)\n",
    "    parser.add_argument(\"--action_type\", type=str, default=\"complex\")\n",
    "    parser.add_argument('--lr', type=float, default=1e-4)\n",
    "    parser.add_argument('--gamma', type=float, default=0.9, help='discount factor for rewards')\n",
    "    parser.add_argument('--tau', type=float, default=1.0, help='parameter for GAE')\n",
    "    parser.add_argument('--beta', type=float, default=0.01, help='entropy coefficient')\n",
    "    parser.add_argument(\"--num_local_steps\", type=int, default=50)\n",
    "    parser.add_argument(\"--num_global_steps\", type=int, default=5e6)\n",
    "    parser.add_argument(\"--num_processes\", type=int, default=6)\n",
    "    parser.add_argument(\"--save_interval\", type=int, default=500, help=\"Number of steps between savings\")\n",
    "    parser.add_argument(\"--max_actions\", type=int, default=200, help=\"Maximum repetition steps in test phase\")\n",
    "    parser.add_argument(\"--log_path\", type=str, default=\"tensorboard/A3CSuperMarioLogs\")\n",
    "    parser.add_argument(\"--saved_path\", type=str, default=\"trained_models\")\n",
    "    parser.add_argument(\"--load_from_previous_stage\", type=bool, default=False,\n",
    "                        help=\"Load weight from previous trained stage\")\n",
    "    parser.add_argument(\"--use_gpu\", type=bool, default=False)\n",
    "    args = parser.parse_args('')\n",
    "    return args"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0c7e84b3-c33c-494c-8749-e09c6b4c713d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train(opt):\n",
    "    torch.manual_seed(123)\n",
    "    if os.path.isdir(opt.log_path):\n",
    "        shutil.rmtree(opt.log_path)\n",
    "    os.makedirs(opt.log_path)\n",
    "    if not os.path.isdir(opt.saved_path):\n",
    "        os.makedirs(opt.saved_path)\n",
    "    mp = _mp.get_context(\"spawn\")\n",
    "    env, num_states, num_actions = create_train_env(opt.world, opt.stage, opt.action_type)\n",
    "    global_model = ActorCritic(num_states, num_actions)\n",
    "    if opt.use_gpu:\n",
    "        global_model.cuda()\n",
    "    global_model.share_memory()\n",
    "    if opt.load_from_previous_stage:\n",
    "        if opt.stage == 1:\n",
    "            previous_world = opt.world - 1\n",
    "            previous_stage = 4\n",
    "        else:\n",
    "            previous_world = opt.world\n",
    "            previous_stage = opt.stage - 1\n",
    "        file_ = \"{}/A3CSuperMarioBros{}_{}\".format(opt.saved_path, previous_world, previous_stage)\n",
    "        if os.path.isfile(file_):\n",
    "            global_model.load_state_dict(torch.load(file_))\n",
    "\n",
    "    optimizer = GlobalAdam(global_model.parameters(), lr=opt.lr)\n",
    "    processes = []\n",
    "    for index in range(opt.num_processes):\n",
    "        if index == 0:\n",
    "            process = mp.Process(target=local_train, args=(index, opt, global_model, optimizer, True))\n",
    "        else:\n",
    "            process = mp.Process(target=local_train, args=(index, opt, global_model, optimizer))\n",
    "        process.start()\n",
    "        processes.append(process)\n",
    "    process = mp.Process(target=local_test, args=(opt.num_processes, opt, global_model))\n",
    "    process.start()\n",
    "    processes.append(process)\n",
    "    for process in processes:\n",
    "        process.join()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d9564eb-3c7f-421f-988e-fce30d2ebffb",
   "metadata": {},
   "outputs": [],
   "source": [
    "opt = get_args()\n",
    "train(opt)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
